package com.lagou.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.lagou.entity.User;
import com.lagou.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Reference
    private UserService userService;

    @RequestMapping("/register")
    public String register(User user) {

        String format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        user.setCreatetime(sdf.format(new Date()));
        userService.register(user);
        return "redirect:/user/findAll";
    }

    @RequestMapping("/detail")
    public ModelAndView userDetail(Integer id) {

        User user = userService.findById(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user", user);
        modelAndView.setViewName("detail");

        return modelAndView;
    }

    @RequestMapping("/deleteUser")
    public String deleteUser(Integer id) {

        userService.deleteUser(id);

        return "redirect:/user/findAll";
    }

    @RequestMapping("update")
    public String updateUser(User user) {
        userService.updateUser(user);
        return "redirect:/user/findAll";
    }

    @RequestMapping("/findAll")
    public ModelAndView findAll(String keyword) {

        ModelAndView modelAndView = new ModelAndView();
        List<User> users = userService.findAll(keyword);
        modelAndView.addObject("users", users);
        modelAndView.setViewName("list");

        for (User user : users) {
            System.out.println(user);
        }

        return modelAndView;
    }
}
